<template>
    <div class="buy-ticket">
        <div style="width:100%;">
            <el-divider content-position="center" border-style="dashed">排班基本信息</el-divider>
            <table align="center" width="100%" style="margin-bottom: 60px;">
                <tr v-if="roomVOInfo">
                    <td>{{roomVOInfo.regionName}}</td>
                    <td>{{roomVOInfo.cinemaName}}</td>
                    <td>{{roomVOInfo.cinemaAddress}}</td>
                    <td>{{roomVOInfo.roomName}}</td>
                    <td>{{`${Math.floor(roomVOInfo.start / 30 / 2).toString().padStart(2, '0')}:${((roomVOInfo.start /
                    30 % 2) * 30).toString().padStart(2, '0')} - ${Math.floor(roomVOInfo.end / 30 /
                    2).toString().padStart(2, '0')}:${((roomVOInfo.end / 30 % 2) * 30).toString().padStart(2,
                    '0')}`}}</td>
                </tr>
            </table>
            <el-divider border-style="dashed" content-position="center">请选择座位</el-divider>
        </div>
        <div v-if="seatList.length > 0">
            <div v-for="item1 in row" class="center">
                <el-checkbox v-for="item2 in row" size="large"
                    v-model="seatList[(item1 - 1) * col + item2 - 1].seatStatus"
                    @change="handleSeatChange(item1, item2)"
                    :disabled="seatList[(item1 - 1) * col + item2 - 1].seatStatus == true" />
            </div>
        </div>
    </div>
    <BottomBar>
        <el-scrollbar style="flex: 9;">
            <div>
                <el-tag v-for="item in ticketList" size="large" closable style="margin-right: 20px;"
                    @close="hangdleCloseTag(item)" :type="item.payStatus==1?'danger':'primary'">
                    {{ item.seatRow + "排" + item.seatCol + "座"}}
                </el-tag>
            </div>
        </el-scrollbar>
        <div class="center">
            <el-button type="primary" style="z-index=100;flex: 1;" @click="confirmOrder">查看我的订单</el-button>
        </div>
    </BottomBar>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { getSeatBySchedule } from '../../../api/seat'
import { getRoomBySchedule } from '../../../api/room'
import { addTicket, getTicketByOrder, removeTicketById } from '../../../api/ticket'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus';
import BottomBar from '../../../components/BottomBar.vue';
interface ISeat {
    roomId: number,
    rowId: number,
    colId: number,
    row: number,
    col: number,
    seatStatus: boolean
}

interface roomVO {
    scheduleId: number
    roomId: number
    start: number
    end: number
    moviePrice: number

    regionName: string
    cinemaName: string
    cinemaAddress: string
    roomName: string

}

interface ITicket {
    ticketId?: number
    scheduleId: number
    orderId: string
    roomId: number
    movieId: number
    seatRow: number
    seatCol: number

    payStatus?: number
    checkStatus?: number
    ticketPrice: number
    userId: number
}

let seatList = ref<ISeat[]>([])
let ticketList = ref<ITicket[]>([])
let roomVOInfo = ref<roomVO>()
let row = ref(0)
let col = ref(0)
let timer:any = null
const router = useRouter()
const confirmOrder = () => {
    router.push({
        path: '/my/order',
    })
}

const movieId = router.currentRoute.value.query.movieId as any
const date = router.currentRoute.value.query.date as any
const cinemaId = router.currentRoute.value.query.cinemaId as any
const scheduleId = router.currentRoute.value.query.scheduleId as any
let orderId = router.currentRoute.value.query.orderId as any
const userId = JSON.parse(window.sessionStorage.getItem("currentUser")!).userId
const roomId = ref(0)

getTicketByOrder({ orderId: orderId }).then((res: any) => {
    if (res.code == 200) {
        console.log("根据订单获得电影票", res.data);
        ticketList.value = res.data
    } else {
        ElMessage.error("获取电影票失败")
    }
})

getRoomBySchedule({ movieId: movieId, date: date, cinemaId: cinemaId, scheduleId: scheduleId }).then((res: any) => {
    if (res.code == 200) {
        console.log("购票页面->获得基本信息", res.data);
        roomVOInfo.value = res.data
        roomId.value = res.data.roomId
        getSeatByRoomApi()
    }
    else {
        ElMessage({
            message: res.msg,
            type: 'error'
        })
    }
})


const getSeatByRoomApi = () => {
    getSeatBySchedule({ scheduleId: scheduleId }).then((res: any) => {
        if (res.code == 200) {
            // debugger
            seatList.value = res.data.map((item: any) => {
                return {
                    ...item,
                    seatStatus: item.seatStatus == 1 ? false : true
                }
            })
            console.log("获得的座位信息:", seatList.value)
            row.value = res.data[0].rowNum
            col.value = res.data[0].colNum
        }
    })
}

onMounted(() => {
    // timer = setInterval(() => { 
    //     getSeatByRoomApi()
    // }, 1000)
})

const handleSeatChange = (rw: number, cl: number) => {
    console.log("更改后座位的状态信息：", seatList.value[(rw - 1) * col.value + cl - 1].seatStatus)
    let seatStatus = seatList.value[(rw - 1) * col.value + cl - 1].seatStatus
    //先判断一下这张票的播放时间是否大于播放前的30分钟
    // let now = new Date()
    // let dateParam = date.split("-")
    // let hourParam = (roomVOInfo.value!.start - 30) / 60
    // let minParam = (roomVOInfo.value!.start - 30) % 60
    // let playTime = new Date(
    //     parseInt(dateParam[0]), parseInt(dateParam[1]) - 1, parseInt(dateParam[2]), hourParam, minParam
    // )
    // if(now > playTime) {
    //     console.log(now,playTime)
    //     ElMessage.error("电影播放前的30分钟不允许重选或退票")
    //     return
    // }
    if (seatStatus) {
        let ticket: ITicket = {
            scheduleId: scheduleId,
            roomId: roomId.value,
            movieId: movieId,
            seatRow: rw,
            seatCol: cl,
            ticketPrice: roomVOInfo.value!.moviePrice,
            userId: userId,
            orderId: orderId
        }
        console.log("勾选的座位信息：", ticketList);
        addTicket(ticket).then((res: any) => {
            if (res.code == 200) {
                debugger
                ticketList.value.push(res.data)
                orderId = res.data.orderId
            } else {
                ElMessage.error("购买失败")
            }
        })
    }
}

const hangdleCloseTag = (ticket: ITicket) => {
    const index = ticketList.value.findIndex((item) => {
        return item.seatRow == ticket.seatRow && item.seatCol == ticket.seatCol
    })
    if (ticket.payStatus == 1) {
        ElMessageBox.confirm(
            '取消已支付的电影票，付款将原路返回',
            'Warning',
            {
                confirmButtonText: 'OK',
                cancelButtonText: 'Cancel',
                type: 'warning',
            }
        )
            .then(() => {
                removeTicketById(ticket).then((res: any) => {
                    if (res.code == 200) {
                        ticketList.value.splice(index, 1)
                        seatList.value[(ticket.seatRow - 1) * col.value + ticket.seatCol - 1].seatStatus = false
                    } else {
                        ElMessage.error("删除电影票失败")
                    }
                })

            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '取消退票',
                })
            })
    } else {
        removeTicketById(ticket).then((res: any) => {
            if (res.code == 200) {
                ticketList.value.splice(index, 1)
                seatList.value[(ticket.seatRow - 1) * col.value + ticket.seatCol - 1].seatStatus = false
            } else {
                ElMessage.error("删除电影票失败")
            }
        })
    }

}

onBeforeUnmount(() => {
    clearInterval(timer)
    timer = null;
})
</script>

<style scoped>
.buy-ticket {
    min-height: 60% ;
    padding: 20px 40px;
    height:550px;
    overflow:auto;
}

table td,
table th {
    text-align: center;
}
</style>